package com.fyb.basic.lock.DeadLock;

import java.util.concurrent.TimeUnit;

/**
 * @author ${user}
 * @date 2021-08-10 17:05
 */
public class MyTask implements Runnable {

    private Object myTaskA = null;
    private Object myTaskB = null;

    public MyTask(Object myTaskA, Object myTaskAB) {
        this.myTaskA = myTaskA;
        this.myTaskB = myTaskAB;
    }

    @Override
    public void run() {
        synchronized (myTaskA) {
            System.out.println(String.format("%s 自己持有%s，尝试持有%s",//
                    Thread.currentThread().getName(), myTaskA, myTaskB));
            // 睡两秒 让第二个线程 有足够的时间来获得另一把锁
            try {
                TimeUnit.SECONDS. sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (myTaskB){
                System.out.println(String.format("%s 同时持有%s，尝试持有%s",//
                        Thread.currentThread().getName(), myTaskA, myTaskB));
            }
        }
    }
}
